<template>
  <el-col v-if="auths.select" class="app-v-center app-column" style="overflow-y: auto;">
    <el-row class="app-h-48px app-fill-width app-v-center pl-4 app-bb-1px-l2" style="background: #545c64" :gutter="10">
      <el-button
        size="mini"
        :disabled="!auths.add"
        @click="toAddCustomer()"
      >添加客户</el-button>
      <!-- <el-button
        size="mini"
      >删除</el-button> -->
    </el-row>
    <el-row class="app-h-48px app-fill-width app-v-center" :gutter="10">
      <div class="px-2">
        <el-input v-model="search.name" placeholder="请输入搜索内容" />
      </div>
      <div class="pr-2">
        <el-cascader
          v-model="region1"
          :options="mapJson"
          :placeholder="search.city? `${search.province}/${search.city}`: search.province ? search.province : '请选择地区'"
          :props="{ value: 'name', label: 'name' }"
          @expand-change="addressChange"
          @change="addressChange"
        />
      </div>
      <div class="pr-2">
        <el-select v-model="search.itemId" placeholder="请选择服务项目">
          <el-option v-for="item in itemList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </div>
      <div class="pr-2">
        <el-select v-if="auths.status_select" v-model="search.status" placeholder="请选择状态">
          <el-option label="未完成" :value="0" />
          <el-option label="已完成" :value="1" />
        </el-select>
      </div>
      <div class="pr-2">
        <el-select v-if="auths.create_people" v-model="search.userId" placeholder="请选择创建人">
          <el-option v-for="item in creatorList" :key="item.userId" :label="item.username" :value="item.userId" />
        </el-select>
      </div>
      <div class="pr-2">
        <el-date-picker
          v-model="dates"
          type="datetimerange"
          range-separator="至"
          format="yyyy-MM-dd HH:ss:mm"
          value-format="yyyy-MM-ddTHH:ss:mm.000Z"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="getDates"
        />
      </div>
      <div class="pr-2">
        <el-button size="mini" type="info" @click="getCustomerList">
          搜索
        </el-button>
      </div>
      <div class="pr-2">
        <el-button size="mini" type="primary" @click="resetSearch">
          重置
        </el-button>
      </div>
      <div class="pr-2">
        <el-button size="mini" type="success" @click="copyMobile()">
          一键复制电话
        </el-button>
      </div>
    </el-row>
    <el-table
      border
      :row-style="{height:'30px'}"
      :data="customerList"
      class="app-flex-1"
      style="width: 100%;overflow-y: auto;"
    >
      <el-table-column
        prop="id"
        align="center"
        label="ID"
        width="40"
      >
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>{{ scope.row.id }}</p>
            <div slot="reference" class="app-ellipsis">
              {{ scope.row.id }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        align="center"
        label="姓名"
        width="80"
      >
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="right">
            <p>{{ scope.row.name }}</p>
            <div slot="reference" class="app-ellipsis">
              {{ scope.row.name }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        prop="mobile"
        align="center"
        label="客户电话"
        width="110"
      />
      <el-table-column
        prop="status"
        align="center"
        label="状态"
        width="85"
      >
        <template slot-scope="scope">
          <el-select v-model="scope.row.status" :disabled="(scope.row.status === 0 && !auths.wc_update) || (scope.row.status === 1 && scope.row.isOpen === 1) || (scope.row.status === 1 && !auths.week_update)" :class="[scope.row.status===0 ? 'inc' : 'ded']" placeholder="请选择状态" @change="setStatus(scope.row)">
            <el-option style="color: red" label="未完成" :value="0" />
            <el-option style="color: red" label="已完成" :value="1" />
          </el-select>
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="carNo"
        align="center"
        label="车牌号"
        width="100"
      />
      <el-table-column
        prop="carType"
        align="center"
        label="车型"
        width="80"
      /> -->
      <el-table-column
        prop="itemId"
        align="center"
        label="服务类型"
        width="80"
      >
        <template slot-scope="scope">
          <el-select disabled :value="scope.row.itemId">
            <el-option v-for="item in itemList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        prop="region"
        align="center"
        label="地区"
      >
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="right">
            <p>住址: {{
              scope.row.address ?
                scope.row.province +
                scope.row.city +
                scope.row.county +
                scope.row.address
                :scope.row.province +
                  scope.row.city +
                  scope.row.county
            }}</p>
            <div slot="reference" class="app-ellipsis">
              {{
                scope.row.address ?
                  scope.row.province +
                  scope.row.city +
                  scope.row.county +
                  scope.row.address
                  :scope.row.province +
                    scope.row.city +
                    scope.row.county
              }}
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column
        prop="repairShopMobile"
        align="center"
        label="修理厂电话"
        width="110"
      />
      <el-table-column
        prop="quotation"
        align="center"
        label="报价"
        width="80"
      />
      <el-table-column
        prop="receipts"
        align="center"
        label="实收"
        width="80"
      />
      <el-table-column
        prop="notes"
        align="center"
        label="备注"
        min-width="400"
      >
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>备注: {{ scope.row.notes }}</p>
            <div slot="reference" class="app-ellipsis">
              {{ scope.row.notes || '/' }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        prop="username"
        align="center"
        label="创建人"
        width="70"
      />
      <el-table-column
        prop="createTime"
        align="center"
        label="添加时间"
        width="90"
      >
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>{{ scope.row.createTime.replace('T',' ') }}</p>
            <div slot="reference" class="app-ellipsis">
              {{ scope.row.createTime.replace('T',' ').slice(0,10) }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        prop="completionTime"
        align="center"
        label="完成时间"
        width="90"
      >
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>{{ scope.row.completionTime && scope.row.completionTime.replace('T',' ') }}</p>
            <div slot="reference" class="app-ellipsis">
              {{ scope.row.completionTime && scope.row.completionTime.replace('T',' ').slice(0,10) }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        width="120"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            :disabled="scope.row.status === 1 || !auths.update"
            @click="handleEdit(scope.$index, scope.row)"
          ><i class="el-icon-edit" /></el-button>
          <el-button
            size="mini"
            type="danger"
            :disabled="!auths.delete"
            @click="handleDelete(scope.$index, scope.row)"
          ><i class="el-icon-delete" /></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="app-relative app-fill-width app-h-center">
      <el-pagination
        class="my-2"
        background
        :current-page.sync="pageNo"
        :page-sizes="[10, 20, 50]"
        :page-size.sync="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="getCustomerList"
        @current-change="getCustomerList"
      />
      <div class="app-absolut app-r-0 app-y-center mr-9">
        总实收：{{ allReceipts }}元
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :title="isEdit? '添加用户' : '修改用户'"
      :visible.sync="addCustomerDialog"
      custom-class="app-height-70vh app-scroll-y"
      width="50vw"
    >
      <el-form ref="form" :rules="rules" class="app-width-80p" :model="form" label-width="160px">
        <el-form-item prop="name" label="客户姓名">
          <el-input v-model="form.name" />
        </el-form-item>
        <!-- <el-form-item prop="carNo" label="车牌号">
          <el-input v-model="form.carNo" />
        </el-form-item>
        <el-form-item prop="carType" label="车型">
          <el-input v-model="form.carType" />
        </el-form-item> -->
        <el-form-item prop="itemId" label="服务项目">
          <el-select v-model="form.itemId" placeholder="请选择服务项目">
            <el-option v-for="item in itemList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="mobile" label="客户手机号">
          <el-input v-model="form.mobile" />
        </el-form-item>
        <el-form-item label="地区">
          <el-cascader v-model="region" :options="mapJson" :props="{value: 'name',label: 'name'}" />
        </el-form-item>
        <!-- <el-form-item prop="address" label="详细地址">
          <el-input v-model="form.address" />
        </el-form-item> -->
        <el-form-item prop="repairShopMobile" label="修理厂电话">
          <el-input v-model="form.repairShopMobile" />
        </el-form-item>
        <el-form-item prop="quotation" label="报价">
          <el-input v-model="form.quotation" />
        </el-form-item>
        <el-form-item prop="receipts" label="实收">
          <el-input v-model="form.receipts" />
        </el-form-item>
        <!-- <el-form-item prop="status" label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="未完成" :value="0" />
            <el-option label="已完成" :value="1" />
          </el-select>
        </el-form-item> -->
        <el-form-item prop="notes" label="备注">
          <el-input v-model="form.notes" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addCustomerDialog = false">取 消</el-button>
        <el-button type="info" @click="addCustomer()">确 定</el-button>
      </div>
    </el-dialog>
  </el-col>
  <div v-else class="app-hv-center py-8 app-fill" style="color: grey">
    暂无权限查看
  </div>
</template>

<script>
import { getCustomerCreatorList,getCustomerList,updateCustomer,deleteCustomerById,addCustomer,getItemList,editCustomerStatus } from '@/api/customer'
import { getMapJson } from '@/api/user'
import { mapState } from 'vuex'
export default {
  data: () => ({
    rules: {
      name: [
        { required: true, message: '请输入客户姓名', trigger: 'blur' }
      ]
    },
    isEdit: false,
    addCustomerDialog: false,
    customerList: [],
    pageNo: 1,
    pageSize: 20,
    total: 0,
    mapJson: [],
    dates: [],
    creatorList: [],
    itemList: [],
    allReceipts: 0,
    region: [],
    region1: [],
    form: {
      name: '',
      address: '',
      carNo: '',
      carType: '',
      city: '',
      county: '',
      id: 0,
      itemId: 0,
      mobile: '',
      notes: '',
      province: '',
      quotation: 0,
      receipts: 0,
      repairShopMobile: '',
      status: 0
    },
    search: {
      name: '',
      mobile: '',
      itemId: '',
      status: void 0,
      beginTime: '',
      endTime: '',
      userId: null,
      province: void 0,
      city: void 0,
      county: void 0
    },
    auths: {
      add: false,
      delete: false,
      update: false,
      select: false,
      wc_update: false,
      week_update: false,
      create_people: false,
      status_select: false
    }
  }),
  computed: {
    ...mapState('app',[
      'menuAndAuth'
    ])
  },
  mounted() {
    const menu = this.menuAndAuth.find(m => m.name === '客户管理')
    if (menu) {
      const listmenuauth = menu.children.find(lm => lm.name === '客户列表').children
      this.auths.add = listmenuauth.some(auth => auth.path === 'add')
      this.auths.delete = listmenuauth.some(auth => auth.path === 'delete')
      this.auths.update = listmenuauth.some(auth => auth.path === 'update')
      this.auths.select = listmenuauth.some(auth => auth.path === 'select')
      this.auths.wc_update = listmenuauth.some(auth => auth.path === 'wc_update')
      this.auths.week_update = listmenuauth.some(auth => auth.path === 'week_update')
      this.auths.create_people = listmenuauth.some(auth => auth.path === 'create_people')
      this.auths.status_select = listmenuauth.some(auth => auth.path === 'status_select')
    }
    if (this.auths.select) {
      // 地址信息
      getMapJson().then(res => {
        if (res.code === 200) {
          this.mapJson = JSON.parse(res.data)
        }
      })
      // 项目类型列表
      getItemList().then(res => {
        if (res.code === 200) {
          this.itemList = res.data
        }
      })
      // 创建人列表
      getCustomerCreatorList().then(res => {
        if (res.code === 200) {
          this.creatorList = res.data
        }
      })
      this.getCustomerList()
    } else {
      this.$message({ type: 'error',message: '您暂无权限查看此页面数据' })
    }
  },
  methods: {
    copyMobile() {
      const cs = this.customerList.filter(p => !!p.mobile)
      const ps = cs.map(p => p.mobile)
      const str = ps.join('\n')
      const textArea = document.createElement('textarea')
      textArea.value = str
      // 使text area不在viewport，同时设置不可见
      textArea.style.position = 'absolute'
      textArea.style.opacity = 0
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      return new Promise((res, rej) => {
        // 执行复制命令并移除文本框
        document.execCommand('copy') ? this.$message({
          message: '复制成功',
          type: 'success'
        }) : rej()
        textArea.remove()
      })
    },
    setStatus(item) {
      editCustomerStatus({ id: item.id }).then(res => {
        if (res.code === 200) {
          this.$message({ type: 'success',message: '修改成功' })
          this.getCustomerList()
        }
      })
    },
    getDates(e) {
      this.search.beginTime = e[0]
      this.search.endTime = e[1]
    },
    resetSearch() {
      this.dates = []
      this.region1 = []
      this.search = {
        name: '',
        mobile: '',
        itemId: '',
        status: null,
        beginTime: null,
        endTime: null,
        userId: null,
        province: void 0,
        city: void 0,
        county: void 0
      }
      this.getCustomerList()
    },
    addressChange(e) {
      this.search.province = e[0] || void 0
      this.search.city = e[1] || void 0
      if (e[2]) {
        this.search.county = e[2]
      } else {
        this.region1 = []
        this.search.county = void 0
      }
    },
    toAddCustomer() {
      this.form = {
        name: '',
        mobile: '',
        customername: '',
        password: ''
      }
      this.region = []
      this.isEdit = false
      this.addCustomerDialog = true
    },
    getCustomerList() {
      if (!this.search.userId) {
        delete this.search.userId
      }
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        ...this.search
      }
      getCustomerList(params).then(res => {
        if (res.code === 200) {
          this.customerList = res.data.pageList.dataList
          this.allReceipts = res.data.allReceipts
          this.total = res.data.total
        }
      })
    },
    handleEdit(index,row) {
      this.isEdit = true
      this.form = row
      this.region = [this.form.province,this.form.city,this.form.county]
      this.addCustomerDialog = true
    },
    handleDelete(index,row) {
      this.$confirm(`确认删除客户${row.carNo}？`,'提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCustomerById({ id: row.id }).then(res => {
          if (res.code === 200) {
            this.$message({ type: 'success',message: '已删除' })
            this.pageNo = 1
            this.getCustomerList()
          }
        })
      }).catch(() => {
        this.$message('已取消')
      })
    },
    addCustomer() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.province = this.region[0]
          this.form.city = this.region[1]
          this.form.county = this.region[2]
          if (this.isEdit) {
            updateCustomer(this.form).then(res => {
              if (res.code === 200) {
                this.getCustomerList()
                this.$message({ type: 'success',message: '操作成功' })
                this.addCustomerDialog = false
              }
            })
          } else {
            delete this.form.status
            addCustomer(this.form).then(res => {
              if (res.code === 200) {
                this.pageNo = 1
                this.getCustomerList()
                this.$message({ type: 'success',message: '操作成功' })
                this.addCustomerDialog = false
              }
            })
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-table .cell {
  padding-left: 5px;
  padding-right: 5px;
}
::v-deep .el-table .cell .el-input__inner {
  padding: 0 25px 0 0;
}
::v-deep .inc input {
  color: red !important;
}
::v-deep .ded input {
  color: #a8bf8f !important;
}
::v-deep .el-table td, .el-table th {
  padding: 4px 0;
}
::v-deep .el-input__inner {
  height: 28px;
  line-height: 28px;
}
::v-deep .el-input__icon {
  height: 28px;
  line-height: 28px;
}
// ::v-deep .nav .el-input__inner {
//   height: 30px;
//   line-height: 30px;
// }
// ::v-deep .nav .el-input__icon {
//   height: 30px;
//   line-height: 30px;
// }
::v-deep .el-date-editor .el-range-separator {
    line-height: 22px;
}
</style>
